$(function(){
    var delStatus,departmentId,page,roleId,searchKey,status,can,size,
        trId,allPage,zhi,userId,roleName;

    // 页面初始化    加载部门列表  已经做好;
    function getDepartment()
    {
        $.ajax({
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:getdepartment,
            success:function (data){
                if( data.resultCode == 200 )
                {
                    var departmentList = data.value;
                    for( var i=0;i<departmentList.length;i++ )
                    {
                        $('.department').append('<option value="'+departmentList[i].id+'">'+departmentList[i].name+'</option>');
                    };
                }
                else if( data.resultCode == 515 )
                {
                    reLogin();
                }
                else
                {
                    console.log('接口出错!非200,非515!')
                };
                console.log('加载部门列表接口调通!!!!')
            },
            error:function(){
                console.log('加载部门列表接口请求失败')
            },
        });
    };
    getDepartment();

    //页面初始化     加载从后台获取的角色;     已经做好;
    function getJuese()
    {
        $.ajax({
            type:'get',
            headers: {"Accept-CMS-Token":token},
            url:getrolelist,
            crossDomain:true,
            dataType:'json',
            success:function (data){
                if( data.resultCode == 200 )
                {
                    var jueseList = data.value;
                    for( var i=0;i<jueseList.length;i++ )
                    {
                        $('.jueseList').append('<option value="'+jueseList[i].id+'">'+jueseList[i].roleName+'</option>');
                    };
                }
                else if( data.resultCode == 515 )
                {
                    reLogin();
                }
                else
                {
                    console.log('接口出错!非200,非515!')
                }
                console.log('角色列表接口请求成功!!!!')
            },
            error:function(){
                console.log('角色列表接口请求失败')
            },

        });
    };
    getJuese();

    //页面初始化   账户列表;   已经做好,就差封装传参;是为了搜索功能;
    accountList( '',1,'','',10,0 );
    //初始化总页数
    getPage(allPage);

    //将加载   账户列表    的ajax请求封装,,向这个函数里面传参数;
    function accountList( departmentId,page,roleId,searchKey,size,status )
    {
        $.ajax({
            async:false,
            cache:false,
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:getsystemlist,
            data:{
                departmentId:departmentId,
                page:page,
                roleId:roleId,
                searchKey:searchKey,
                size:size,
                status:status
            },
            dataType:'json',
            success:successFn,
            error:function(){
                console.log('账户列表接口请求失败')
            },
        });
        return allPage;
    };

    //向后台请求参数,,,如果请求成功,,,就执行该函数,,,
    function successFn( data )
    {

        if( data.resultCode == 200 )
        {
            // alert(1)
            if( data.value.infolist == '' )
            {
                clearTable();
                $('.account_admin tbody').append('<tr><td></td><td></td><td></td><td>您搜索的内容不存在</td><td></td><td></td><td></td></tr>');
                hintUser();
                return allPage = 1;
            }
            else
            {
                var infolist = data.value.infolist;
                allPage = data.count;
                if( infolist.length > 0 )
                {
                    //清空表格
                    clearTable();

                    // 将storage中的userName取出来...做判断...如果相同的话...就加一个类名dis...使这个按钮禁用...也不可删除..
                    var username = JSON.parse(base.decode(localStorage.getItem( base.encode('userinfo') )) ).username;
                    //先生成表格,最后在生成禁用启用的点击事件;;;;;如果表格上的是启用那么就是禁用;,最后在为这写生成的a添加点击事件发送请求;
                    for( var i=0;i<infolist.length;i++ )
                    {
                        $('.account_admin').append('<tr userId="'+infolist[i].userId+'"></tr>');//属性

                        $('.account_admin tr').eq(i+1).append('<td>'+(i+1)+'</td>');

                        $('.account_admin tr').eq(i+1).append('<td>'+infolist[i].userName+'</td>');

                        $('.account_admin tr').eq(i+1).append('<td>'+infolist[i].name+'</td>');

                        $('.account_admin tr').eq(i+1).append('<td>'+infolist[i].departmentName+'</td>');

                        $('.account_admin tr').eq(i+1).append('<td>'+infolist[i].roleName+'</td>');

                        $('.account_admin tr').eq(i+1).append('<td>'+change(infolist[i].delStatus)+'</td>');

                        if( username == infolist[i].userName )
                        {
                            $('.account_admin tr').eq(i+1).append('<td><a class="ed ed-account">编辑</a><a class="ed dis">删除</a></td>');
                            roleName = infolist[i].roleName;

                        }
                        else
                        {
                            $('.account_admin tr').eq(i+1).append('<td><a class="ed ed-account">编辑</a><a class="ed del_account">删除</a></td>')
                        };


                    };
                    var zhuang;
                    for( var j=0;j < infolist.length;j++)
                    {//为表格当中的最后一项添加禁用或者启用的按钮...
                        zhuang = $('.account_admin tr').eq(j+1).children('td').eq(5);
                        if( zhuang.html() != '' )
                        {
                            if( zhuang.html() == '启用' )
                            {
                                // 将storage中的userName取出来...做判断...如果相同的话...就加一个类名dis...使这个按钮禁用...也不可删除..
                                if( username == infolist[j].userName )
                                {
                                    $('.account_admin tr').eq(j+1).children('td').eq(6).append('<a class="dis">禁用</a>');//操作
                                }
                                else
                                {
                                    $('.account_admin tr').eq(j+1).children('td').eq(6).append('<a class="stop">禁用</a>');//操作
                                };

                            }
                            else if( zhuang.html() == '禁用' )
                            {
                                $('.account_admin tr').eq(j+1).children('td').eq(6).append('<a class="stop">启用</a>');//操作
                            };

                        };
                    };
                }
                else
                {//要搜索的账户不存在
                    return allPage = 1;
                    clearTable();
                    $('.account_admin').append('<tr><td></td><td></td><td>您搜索的内容不存在</td><td></td><td></td><td></td></tr>');
                    hintUser();
                };
            };
        }
        else if(data.resultCode == 515)
        {
            reLogin();
        }
        else
        {
            clearTable();
            $('.account_admin').append('<tr><td></td><td></td><td>您搜索的内容不存在</td><td></td><td></td><td></td></tr>');
            hintUser();
            return allPage = 1;
        };
        console.log('账户列表接口请求成功!!!!')
    }

    //清空表格当中的数据,并且追加表头
    function clearTable()
    {
        $('.account_admin').html('');

        $('.account_admin').append('<thead><tr><th>序号</th><th>用户名称</th><th>姓名</th><th>部门</th><th>角色</th><th>状态</th><th>操作</th></tr></thead><tbody></tbody>');

    };

    //整个页面的搜索功能!!!  向   accountList这个函数里面传参数
    $('.search-account').click(function(){
        departmentId = $('.department').children('option:selected').val();
        page = 1;
        roleId = $('.jueseList').children('option:selected').val();
        searchKey = $('input[name = sou-account-cont]').val();
        size = 10;
        status = $('.status-all').children('option:selected').val();
        zhi = accountList( departmentId,page,roleId,searchKey,size,status );
        if( zhi==0 )
        {
            zhi = 1;
            getPage(zhi);
        }
        else
        {
            getPage(zhi);
        };
        // $('input[name = sou-account-cont]').val('')
    });

    //当输入文本框中时,,,按下enter键,,,发起搜索,,,按下键盘中的shift+enter键时向后台发起搜索,,
    $(document).keydown(function(event){
        var ev = ev || event;
        // console.log(ev.keyCode)
        if( ev.keyCode == 13 )
        {
            departmentId = $('.department').children('option:selected').val();
            page = 1;
            roleId = $('.jueseList').children('option:selected').val();
            searchKey = $('input[name = sou-account-cont]').val();
            size = 10;
            status = $('.status-all').children('option:selected').val();
            zhi = accountList( departmentId,page,roleId,searchKey,size,status );
            if( zhi==0 )
            {
                zhi = 1;
                getPage(zhi);
            }
            else
            {
                getPage(zhi);
            };

        };
    });

    //点击禁用,,,,向后台发送请求,,,,并且前端状态也发生改变;
    $(document).on('click','.stop',function(){
        var stopCont = $(this).html();
        userId = $(this).parent('td').parent('tr').attr('userid');
        if( stopCont == '禁用' )
        {
            $(this).parent('td').parent('tr').children('td').eq(5).html('禁用');
            $(this).html('启用');
            //向后台发送请求;delStatus:0;
            enOrDis( huanYuan(stopCont),userId,2 );
        }
        else
        {
            $(this).parent('td').parent('tr').children('td').eq(5).html('启用');
            $(this).html('禁用');
            // 向后台送请求;delStatus:1;
            enOrDis( huanYuan(stopCont),userId,1 );
        };
        // console.log(huanYuan(stopCont)+':'+userId)
    });

    //0和1转变成状态:启用,禁用,全部;
    function change( a )
    {
        if( a == 0 )
        {
            return '启用';
        }
        else if( a == 1 )
        {
            return '禁用';
        };
    };

    //将启用,禁用状态转换成0或者1,,,,
    function huanYuan(a)
    {
        if(  a == '启用' )
        {
            return 0;
        }
        else if( a == '禁用' )
        {
            return 1;
        };
    };

    //点击启用或者禁用按钮的时候向后台传参数;
    function enOrDis( delStatus,userId,statusType )
    {
        $.ajax({
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:saveorupdate,
            data:{
                delStatus:delStatus,
                userId:userId,
                statusType:'1'
            },
            dataType:'json',
            success:function (data){
                if( data.resultCode == 200 )
                {
                    // console.log(data)成功!
                }
                else if( data.resultCode == 515 )
                {
                    reLogin();
                }
                console.log('禁用还是启用接口请求成功!!!!')
            },
            error:function(){
                console.log('禁用还是启用接口请求失败')
            },
        });
    };

    //分页插件的封装,方便多次调用
    function getPage(allPage)
    {
        $('.M-box2').pagination({
            pageCount:allPage,
            jump:true,
            coping:true,
            homePage:'首页',
            endPage:'末页',
            prevContent:'上页',
            nextContent:'下页',
            callback:function (api){//当点击页面当中的时候,会出发这个callback函数;;;;
                var page = api.getCurrent()+"";//得到的是要跳转到的那一页的页码;
                accountList( '',page,'','',10,0 );
            }
        });
    };
    // 每一个下拉菜单发生变化的时候,,,,向后台请求,,,对应的列表发生变化;
    function changeXiaLa(x)
    {
        $(x).change(function (){
            departmentId = $('.department').children('option:selected').val();
            page = 1;
            roleId = $('.jueseList').children('option:selected').val();
            searchKey = $('input[name = sou-account-cont]').val();
            size = 10;
            status = $('.status-all').children('option:selected').val();
            zhi = accountList( departmentId,page,roleId,searchKey,size,status );
            if( zhi==0 )
            {
                zhi = 1;
                getPage(zhi);
            }
            else
            {
                getPage(zhi);
            };
        });
    };
    changeXiaLa('.department');
    changeXiaLa('.jueseList');
    changeXiaLa('.status-all');

    // 点击删除账户....出现弹框...
    $(document).on('click','.del_account',function () {
        userId = $(this).parent('td').parent('tr').attr('userid');
        $('.mask-change').show()
        $('.delete-zhanghu').show();
    });

    // 确定删除账户....跟后台交互....
    $('.sure-del-zhanghu').click(function () {
        console.log(userId);
        $.ajax({
            type:'post',
            headers: {"Accept-CMS-Token":token},
            url:deleteuser,
            data:{
                userId:userId
            },
            dataType:'json',
            success:function (data){
                if( data.resultCode == 200 )
                {
                    $('.mask-change').hide()
                    $('.delete-zhanghu').hide();
                    departmentId = $('.department').children('option:selected').val();
                    page = 1;
                    roleId = $('.jueseList').children('option:selected').val();
                    searchKey = $('input[name = sou-account-cont]').val();
                    size = 10;
                    status = $('.status-all').children('option:selected').val();
                    zhi = accountList( departmentId,page,roleId,searchKey,size,status );
                    if( zhi==0 )
                    {
                        zhi = 1;
                        getPage(zhi);
                    }
                    else
                    {
                        getPage(zhi);
                    };
                }
                else if( data.resultCode == 515 )
                {
                    reLogin();
                }
                else
                {
                    console.log('接口出错!非200,非515!')
                }
                console.log(data)
                console.log(' 永久删除用户接口请求成功!!!!')
            },
            error:function(){
                console.log(' 永久删除用户请求失败')
            },
        })
    });

    // 设置当前账户不可禁用...不可删除...



    // 为二级菜单所对应的页面中设置显示新增,编辑,删除这些按钮...用地址栏对应的id作为判断条件...后台返回来的数据是:新增,编辑,状态,
    var changeId = $.getUrlParam('id');
    var btnStatus = [];
    var userId = localStorage.getItem('陈');
    if(userId == null)
    {
        alert('亲,不好意思,请重新登录!')
        window.location.href = login_jump;
    };
    var information = JSON.parse( base.decode(localStorage.getItem( userId )) );
    var ul_li_permissionlist = information.ul_li_permissionlist;//三级菜单中的数据

    function showBtnStatus()
    {
        flagOuter:for( var i=0;i< ul_li_permissionlist.length;i++)
        {
            for( var j=0;j<ul_li_permissionlist[i].length;j++ )
            {
                if( ul_li_permissionlist[i][j].length > 0 )
                {
                    for( var q=0;q<ul_li_permissionlist[i][j].length;q++ )
                    {
                        if( ul_li_permissionlist[i][j][q].pid == changeId )
                        {
                            btnStatus = ul_li_permissionlist[i][j];
                            break flagOuter;
                        };
                    };
                }
            };
        };
        if( btnStatus.length > 0 )
        {
            for( var x=0;x<btnStatus.length;x++ )
            {
                if( btnStatus[x].permissionName == '新增' )
                {
                    $('.xinzeng').show();
                }
                else if( btnStatus[x].permissionName == '编辑' )
                {
                    $('.ed-account').show();
                }
                else if( btnStatus[x].permissionName == '状态' )
                {
                    $('.stop').show();
                }
                else
                {
                    $('.xinzeng').hide();
                    $('.ed-account').hide();
                    $('.stop').hide();
                }
            };
        }
        else
        {
            $('.xinzeng').hide();
            $('.ed-account').hide();
            $('.stop').hide();
        };
    };

    if( changeId != null )
    {
        showBtnStatus();
    };

    //点击编辑,跳转到编辑页面;还要向下一页传参数;       已经做好
    $(document).on('click','.ed-account',function(){
        can = $(this).parent('td').parent('tr').attr('userid');
        window.location.href = edit_account +'?userId='+can+'&id='+changeId ;
    });

    // 为跳转页面赋值
    $('.xinzeng a').attr( 'href','add_account.html?id='+changeId );

    // 将roleName存到storage里面...为角色管理页面设置当前账户对应的角色不可删除做准备....
    // localStorage.setItem(base.encode('角色名称'),base.encode(roleName));
    // console.log(JSON.parse(base.decode(localStorage.getItem( base.encode('userinfo') )) ))


});



